#!/bin/bash
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/sys_check.sh"
use_tsinghua_conda_channels() {
    echo "use Tsinghua conda mirror"
    export CONDA_CHANNELS='https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main,https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/r,https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/msys2'
}

use_hit_conda_channels() {
    echo "use HIT conda mirror"
    export CONDA_CHANNELS='https://mirrors.hit.edu.cn/anaconda/pkgs/main,https://mirrors.hit.edu.cn/anaconda/pkgs/r,https://mirrors.hit.edu.cn/anaconda/pkgs/msys2'
}

set_nju_conda_channels() {
    echo "use NJU conda mirror as sub"
    export CONDA_CHANNELS_SUB='https://mirror.nju.edu.cn/anaconda/pkgs/main,https://mirror.nju.edu.cn/anaconda/pkgs/r,https://mirror.nju.edu.cn/anaconda/pkgs/msys2'
}

set_aliyun_pip_index() {    
    export PIP_INDEX_URL='https://mirrors.aliyun.com/pypi/simple/'
    export PIP_INDEX_URL_SUB='https://mirrors.nju.edu.cn/pypi/web/simple/'
}

set_nju_pip_index() {    
    export PIP_INDEX_URL='https://mirrors.nju.edu.cn/pypi/web/simple/'
    export PIP_INDEX_URL_SUB='https://mirrors.aliyun.com/pypi/simple/'
}

if [ -n "$GITHUB_PROXY" ]; then
    conda config --set show_channel_urls yes
    url="https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main/win-64/_pytorch_select-1.2.0-gpu.conda"

    NO_REVOKE_PARAM=""
    
    if current_os_is_windows; then
        NO_REVOKE_PARAM="--ssl-no-revoke"
    fi

    status_code=$(curl $NO_REVOKE_PARAM -o /dev/null -s -w "%{http_code}\n" "$url")

    echo "Detect tsinghua conda mirror: "$status_code

    if [ "$status_code" -eq 200 ]; then
        echo "Access to tsinghua mirror is allowed."
        use_tsinghua_conda_channels
    else
        echo "Access to tsinghua mirror is denied. HTTP status code: $status_code."
        use_hit_conda_channels
    fi

    set_nju_conda_channels

    conda config --remove channels https://mirrors.aliyun.com/anaconda/pkgs/main 2>/dev/null
    conda config --remove channels https://mirrors.aliyun.com/anaconda/pkgs/free 2>/dev/null


    url="https://mirrors.nju.edu.cn/pypi/web/packages/ac/bf/ab0fbc97d4b2a603789b24ad993a1a97eea65114ecd9ff6aebe6d6e49cf7/gradio-0.1.0.tar.gz"
    # url="https://mirrors.aliyun.com/pypi/web/packages/ac/bf/ab0fbc97d4b2a603789b24ad993a1a97eea65114ecd9ff6aebe6d6e49cf7/gradio-0.1.0.tar.gz"

    status_code=$(curl $NO_REVOKE_PARAM -o /dev/null -s -w "%{http_code}\n" "$url")

    echo "Detect nju pip mirror: "$status_code

    if [ "$status_code" -eq 200 ]; then
        echo "Access to nju pip index is allowed."
        set_nju_pip_index
    else
        echo "Access to nju index is denied. HTTP status code: $status_code. use aliyun pip index"
        set_aliyun_pip_index
    fi
    
fi
